<template>
  <PageContainer>
    <Header title="选择身份">
      <view class="hb-h-9 hb-box-content hb-py-2 hb-px-4">
        <TSearch text="搜索" @confirm="handleConfirm"></TSearch>
      </view>
      <view class="hb-h-10 hb-bg-[#FFF4E7] hb-flex hb-items-center hb-px-4">
        <TmIcon name="ali-icon icon-tips" color="#E29942" :font-size="32" />
        <TmText
          _class="hb-ml-2"
          label="左滑可编辑/删除标签"
          :line-height="44"
          color="#E29942"
          :font-size="28"
        />
      </view>
    </Header>
    <view>
      <view class="hb-p-4">
        <TmSlideSwitchGroup :active-open-id="activeOpenId">
          <TmRadioGroup v-model="selected">
            <template v-for="v in circleIdentityListData" :key="v.id">
              <TmSlideSwitch
                class="hb-mb-3 hb-rounded-lg hb-box-shadow-base"
                :width="686"
                :height="136"
                transparent
                :id="v.id"
                @open="() => (activeOpenId = v.id)"
              >
                <template #right>
                  <view
                    class="hb-h-full hb-flex hb-items-center hb-justify-end hb-rounded-lg hb-overflow-hidden"
                  >
                    <view
                      class="hb-flex-1 hb-h-full hb-bg-[#EA5E0E] hb-flex hb-items-center hb-justify-end"
                    >
                      <view
                        class="hb-w-13 hb-h-full hb-flex hb-items-center hb-justify-center"
                        @click="handleShowDeleteModal(v)"
                      >
                        <TmText label="删除" color="#fff" :font-size="28" />
                      </view>
                    </view>
                    <view
                      class="hb-w-13 hb-h-full hb-bg-primary hb-flex hb-items-center hb-justify-center"
                      @click="handleShowEditModal(v)"
                    >
                      <TmText label="编辑" color="#fff" :font-size="28" />
                    </view>
                  </view>
                </template>
                <view class="hb-p-3 hb-h-full hb-flex hb-items-center hb-bg-white hb-rounded-lg">
                  <TmRadio :margin="[0, 0, 24, 0]" :size="40" :value="v.id" />
                  <view
                    class="hb-flex-1 hb-flex hb-flex-col hb-justify-between"
                    @click="handleSelectItem(v)"
                  >
                    <TmText _class="hb-font-bold text-overflow-1" :label="v.name" :font-size="32" />
                    <TmText
                      v-if="v.cirCleBotList?.length > 0"
                      :label="v.cirCleBotList.join('，')"
                      _class="text-overflow-1 hb-mt-1"
                      color="#969799"
                      :font-size="24"
                    />
                  </view>
                </view>
              </TmSlideSwitch>
            </template>
          </TmRadioGroup>
        </TmSlideSwitchGroup>

        <Empty v-if="circleIdentityListData.length === 0" />
        <view
          class="hb-h-18 hb-flex hb-items-center hb-justify-center hb-bg-white hb-rounded-[8rpx] hb-border hb-border-dashed hb-border-[#EBEDF0]"
          @click="handleShowCreateModal"
        >
          <TmIcon name="tmicon-plus" :font-size="32" />
          <TmText _class="hb-ml-2" label="新建身份" :font-size="28" />
        </view>
      </view>
      <BottomSubmit submit-btn-label="确认选择" @submit="handleSelectSubmit" />

      <TmModal
        v-model:show="showCreateModal"
        ok-text="保存"
        :overlay-click="false"
        :ok-close="false"
        :height="420"
        splitBtn
        :title="editItem ? '编辑身份' : '新建身份'"
        @ok="handleCreateLabel"
        @cancel="handleCancelCreateModal"
      >
        <template>
          <TmForm
            ref="formRef"
            v-model="formData"
            layout="vertical"
            :padding="[0, 0]"
            :margin="[0, 0, 0, 0]"
            :transparent="true"
            :border="false"
          >
            <TmFormItem
              label="身份名称"
              :show-top-error-gap="false"
              required
              :margin="[0, 0]"
              :padding="[0, 0]"
              :transparent="true"
              field="name"
              :rules="rules"
            >
              <TmInput
                v-model="formData.name"
                :font-size="28"
                :height="88"
                show-char-number
                :maxlength="20"
                placeholder="请输入"
              />
            </TmFormItem>
          </TmForm>
        </template>
      </TmModal>

      <TmModal
        v-model:show="deleteModalVisible"
        title="删除标签"
        :height="300"
        :follow-theme="false"
        cancel-text="取消"
        cancel-color="#969799"
        ok-color="#EA5E0E"
        ok-text="确认删除"
        :ok-close="false"
        @ok="handleDeleteIdentity"
      >
        <view class="hb-text-sm hb-text-[#333] hb-text-center">
          <text>确定要删除“</text>
          <text class="hb-text-primary">{{ deleteItem?.name }}</text>
          <text>”吗？删除后对应好友的标签将会被删除。</text>
        </view>
      </TmModal>
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /* selectMemberIdentity 选择身份 */
  import {
    circleDeleteCircleIdentity,
    circleIdentityList,
    circleUpdateCircleIdentity,
    createCircleIdentity,
  } from '@/api/contact';
  import { CircleIdentityListResult } from '@/api/contact/types';
  import { SelectMemberIdentity } from '@/router/types/modules';
  import TmForm from '@/tmui/components/tm-form/tm-form.vue';
  import { Toast } from '@/utils';

  let success: SelectMemberIdentity['success'];
  const selected = ref<number>();
  const showCreateModal = ref(false);
  const activeOpenId = ref<number>(-1);

  const circleId = ref<number>(0);
  const circleIdentityListData = ref<CircleIdentityListResult[]>([]);
  const allData = ref<CircleIdentityListResult[]>([]);
  const getLabelList = async (keyWord?: string) => {
    const res = await circleIdentityList({ id: circleId.value, keyWord });
    circleIdentityListData.value = res;
    if (!keyWord) allData.value = res;
  };

  const oldSelected = ref<number>();
  customOnload<'selectMemberIdentity'>(async (op) => {
    circleId.value = op.circleId;
    await getLabelList();
    if (op.selected) {
      selected.value = op.selected;
      oldSelected.value = op.selected;
    }
    success = op.success;
  });

  const handleSelectItem = (v: CircleIdentityListResult) => {
    activeOpenId.value = -1;
    if (selected.value === v.id) {
      selected.value = void 0;
    } else {
      selected.value = v.id;
    }
  };

  const rules = ref([{ required: true, message: '请输入身份名称' }]);
  const formRef = ref<InstanceType<typeof TmForm>>();
  const formData = reactive({
    name: '',
  });

  const deleteModalVisible = ref(false);
  const deleteItem = ref<CircleIdentityListResult>();

  const handleShowDeleteModal = (v: CircleIdentityListResult) => {
    activeOpenId.value = -1;
    deleteItem.value = v;
    deleteModalVisible.value = true;
  };

  const handleDeleteIdentity = () => {
    circleDeleteCircleIdentity({ id: deleteItem.value!.id }).then((res) => {
      Toast('删除成功');
      if (selected.value === deleteItem.value!.id) {
        selected.value = void 0;
      }
      deleteModalVisible.value = false;
      circleIdentityListData.value = circleIdentityListData.value.filter(
        (item) => item.id !== deleteItem.value!.id,
      );
      if (oldSelected.value === deleteItem.value!.id) {
        success?.();
      }
    });
  };

  const editItem = ref<CircleIdentityListResult>();
  const handleShowEditModal = (v: CircleIdentityListResult) => {
    activeOpenId.value = -1;
    formRef.value?.clearValidate();
    showCreateModal.value = true;
    editItem.value = v;
    formData.name = v.name;
  };

  const handleCancelCreateModal = () => {
    formData.name = '';
    editItem.value = void 0;
  };

  function handleShowCreateModal() {
    activeOpenId.value = -1;
    showCreateModal.value = true;
    formRef.value?.clearValidate();
  }

  function handleCreateLabel() {
    formRef.value?.submit();
    const res = formRef.value?.validate();
    if (res?.isPass) {
      if (editItem.value) {
        circleUpdateCircleIdentity({ id: editItem.value.id, name: formData.name }).then((res) => {
          Toast('更新成功');
          showCreateModal.value = false;
          circleIdentityListData.value = circleIdentityListData.value.map((item) => {
            if (item.id === editItem.value!.id) {
              allData.value.find((item) => item.id === editItem.value!.id)!.name = formData.name;
              return { ...item, name: formData.name };
            }
            return item;
          });
          formData.name = '';
          handleSelectSubmit(false);
        });
      } else {
        createCircleIdentity({ circleId: circleId.value, name: formData.name }).then((res) => {
          Toast('创建成功');
          showCreateModal.value = false;
          getLabelList();
          formData.name = '';
        });
      }
    }
  }

  /** 搜索 */
  const handleConfirm = (val: string) => {
    getLabelList(val);
  };

  const handleSelectSubmit = (isBack: boolean = true) => {
    const item = allData.value.find((item) => item.id === selected.value);
    if (item) {
      success?.({
        id: item?.id,
        name: item?.name,
      });
    } else {
      success?.();
    }
    if (isBack) {
      navigateBack();
    }
  };
</script>

<style lang="scss" scoped></style>
